package com.dycong.common.mybatis.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import static org.apache.commons.lang3.CharEncoding.UTF_8;

@Slf4j
public class ColumnLengthControlUtil {

    private final static Integer DEFAULT_MAX_LENGTH = 200;

    public static String emojiMaxLimitHandle(String data, Integer maxLength) {
        if (StringUtils.isEmpty(data)) {
            return null;
        }
        if (maxLength <= 0) {
            maxLength = DEFAULT_MAX_LENGTH;
        }
        try {
            return findSubResult(data, maxLength);
        } catch (Exception e) {
            log.error("emojiMaxLimitHandle data={}, maxLimit={}", data, maxLength, e);
        }
        return data;
    }

    /**
     * 递归循环去验证是否达到了数据库的column的上限值
     *
     * @param data
     * @param maxLimit
     * @throws UnsupportedEncodingException
     */
    private static String findSubResult(String data, Integer maxLimit) throws UnsupportedEncodingException {
        //获取没裁剪加密后的string
        String subtractionStr = URLEncoder.encode(data, UTF_8);
        //初始化没裁剪的长度
        int length = data.length();
        //初始化没裁剪的长度
        int subtraction = subtractionStr.length();

        //最终的裁剪结果
        String subResult = data;
        //长度跟数据库长度比较,如果大于或等于则裁剪
        while (subtraction >= maxLimit) {
            //第一次是用删除表情符后的str来进行比较
            String subData = StringUtils.substring(data, 0, length--);
            subtraction = URLEncoder.encode(subData, UTF_8).length();
            subResult = subData;
        }
        if (StringUtils.isEmpty(subResult)) {
            log.error("findSubResult empty data={}, maxLimit={} subResult={}", data, maxLimit, subResult);
            return data;
        }
        return subResult;
    }

}
